package com.love.utils.http;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



public class HttpHelper {
	private static final Logger logger = LoggerFactory.getLogger(HttpHelper.class);
	private static final int RESPONSE_OK = 200;

	public static String doGet(String url, Map<String, String> params) throws Exception{
		//组装参数
		if(params != null && !params.isEmpty()){
			StringBuilder paramSB = new StringBuilder();
			for (String key : params.keySet()) {
				paramSB.append(key)
					   .append("=")
					   .append(params.get(key))
					   .append("&");
			}
			if(paramSB.length() > 0){
				url = url + "?" + paramSB.toString();
				url = url.substring(0, url.length() - 1);
			}
		}
		
		String result = null;
		CloseableHttpClient httpclient = HttpClientBuilder.create().build();
		try {
			HttpGet httpGet = new HttpGet(url);
			HttpResponse httpResponse = httpclient.execute(httpGet);
			if (httpResponse.getStatusLine().getStatusCode() == RESPONSE_OK) {
				HttpEntity httpEntity = httpResponse.getEntity();
				// 取出应答字符串
				result = EntityUtils.toString(httpEntity);
				logger.info("http get请求成功：url={}, result={}", url, result);
				// 一般来说都要删除多余的字符，去掉返回结果中的"\r"字符，否则会在结果字符串后面显示一个小方格
				result.replaceAll("\r", "");
			}else{
				logger.info("Http get请求失败：url={}, result={}", url, EntityUtils.toString(httpResponse.getEntity()));
			}
		} catch (Exception e) {
			logger.error("Http get请求异常：url={}, exception={}", url, e.getMessage());
			throw e;
		} finally {
			try {
				httpclient.close();
			} catch (IOException e) {
				logger.error("Http get请求close异常：url={}, exception={}", url, e.getMessage());
				throw e;
			}
		}
		return result;
	}
	
	public static String doPost(String url, Map<String, String> params) throws Exception{
		String result = null;
		CloseableHttpClient httpclient = HttpClientBuilder.create().build();
		try {
			HttpPost httpost = new HttpPost(url);
			if (params != null && !params.isEmpty()) {
				List<NameValuePair> paramList = new ArrayList<NameValuePair>();
				for (String key : params.keySet()) {
					paramList.add(new BasicNameValuePair(key, params.get(key))); 
				}
				httpost.setEntity(new UrlEncodedFormEntity(paramList, "utf-8"));
			}
			HttpResponse httpResponse = httpclient.execute(httpost);
			if (httpResponse.getStatusLine().getStatusCode() == RESPONSE_OK) {
				HttpEntity httpEntity = httpResponse.getEntity();
				// 取出应答字符串
				result = EntityUtils.toString(httpEntity);
				logger.info("http post请求成功：url={}, params={}, result={}", url, params, result);
				// 一般来说都要删除多余的字符，去掉返回结果中的"\r"字符，否则会在结果字符串后面显示一个小方格
				result.replaceAll("\r", "");
			}else{
				logger.info("http post请求失败：url={}, params={}, result={}", url, params, EntityUtils.toString(httpResponse.getEntity()));
			}
		} catch (Exception e) {
			logger.error("Http post请求异常：url={}, params={}, exception={}", url, params, e.getMessage());
			throw e;
		} finally {
			try {
				httpclient.close();
			} catch (IOException e) {
				logger.error("Http post请求异常：url={}, params={}, exception={}", url, params.toString(), e.getMessage());
				throw e;
			}
		}
		return result;
	}
	
	
	public static void main(String[] args) {
		try {
			String result = doGet("http://www.baidu.com", null);
			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		try {
			String result = doPost("http://www.baidu.com", null);
			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		try {
			Map<String, String> params = new HashMap<String, String>();
			params.put("abc", "abc");
			params.put("123", "123");
			String result = doPost("http://www.baidu.com", params);
			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
